# -*- encoding: utf-8 -*- 
from datetime import datetime, timedelta
from openerp import SUPERUSER_ID
from openerp import api, fields, models, _
import openerp.addons.decimal_precision as dp
from openerp.exceptions import UserError
from openerp.tools import float_is_zero, float_compare, DEFAULT_SERVER_DATETIME_FORMAT
import os
import shutil

class fhcode_tb_table002(models.Model):
    _name = 'fhcode.tb_table002'
    _description = u'对象表'
    _rec_name='name'
    _order='create_date DESC'	
    def get_employee(self):
        obj = self.env['hr.employee']
        idsobj = obj.search([('user_id','=',self.env.user.id)])
        print('-------------------------------------')		
        print(self.env.user.id)		
        #print(ids)	
        res = idsobj.read()
        print(res)					
        return res and res[0]['id'] or 0				
    name= fields.Char(u'英文',readonly=False,required=False,translate=False)
    description= fields.Char(u'中文',readonly=False,required=False,translate=False)
    rec_name= fields.Char(u'显示内容',readonly=False,required=False,translate=False)
    orde= fields.Char(u'排序',readonly=False,required=False,translate=False)
    inherit= fields.Char(u'继承对象',readonly=False,required=False,translate=False)
	
    name002= fields.Text(u'SQL',readonly=False,required=False,translate=False)	
    #name003= fields.Char(u'_depend',readonly=False,required=False,translate=False)	
    modle_id = fields.Many2one('fhcode.tb_modle', string=u'模块')  	
    Ftype=fields.Selection([('0',u'表单'),('1',u'列表'),('2',u'向导'),('3',u'视图')],u'生成代码类型',readonly=False,required=False,translate=False)  
					   
    FDisable=fields.Selection([('0',u'是'),('1',u'否')],u'是否启动打印',readonly=False,required=False,translate=False)
    order_line = fields.Many2many("fhcode.tb_base", 'fhcode_tbtable2_tbbase_rel', 'uid', 'gid', string=u'基本字段',)#fields.One2many('fhcode.tb_table002line', 'pay_id', string='Order Lines', copy=True)

	
    @api.multi
    @api.onchange('FAddperson')	
    def FClassbb_id_change(self):
        vals={}
        #raise osv.except_osv(_('提示2!'), _(FSchedule))
        tinfo_FSchedule=None
        tinfo_ID=0
        tinfo_FSubject=""		
        if self.FAddperson.id !=False :
		
            prod_line_ids002=self.env['hr.employee'].search([('id','=',self.FAddperson.id)])
            tinfo_FSchedule=self.env['hr.employee'].browse(prod_line_ids002)
            for n in tinfo_FSchedule:
                tinfo_ID=n.id				
        vals={'fdepartment':tinfo_ID}
        return {'value': vals}
    @api.multi
    def print_quotation(self):

        path=self.modle_id.fpath
        path2=self.modle_id.fpath2		
        t=os.path.exists(path)
        if(t==False):
            self.os_mkdir(path)



	
        #打印报表
	    #取模块的路径,没有则创建
        path=self.modle_id.fpath+"\\view"
        path2=self.modle_id.fpath2		
        t=os.path.exists(path)
        if(t==False):
            self.os_mkdir(path)
        oldname= path2+"\\Template\\view\\__init__.py"
        newname=path+"\\__init__.py"
        shutil.copyfile(oldname,newname)			

        if(1==1):
            self.os_readlines_py(path2+"\\Template\\view\\sale_report.py",path+"\\"+self.modle_id.fname+"_"+self.name+".py")
		
        return True

    def os_mkdir(self,path):

        os.mkdir(path)      
        return True	
    def os_readlines_py(self,path,path2):

        # 打开文件
        fo = open(path, "r", encoding='UTF-8')
        print ("文件名为: ", fo.name)
        print ("文件名为2: ", self.description)
        print ("文件名为3: ", self.modle_id.fname+"."+self.name)
        fieldsII=self.os_fieldsII_py()
        print(fieldsII)		
        lineST=""
        for line in fo.readlines():                          #依次读取每行  
            #line = line.strip()                             #去掉每行头尾空白
            line=line.replace("FHsaasMK",self.modle_id.fname);		
            line=line.replace("FHsaasTB",self.name);  			
            line=line.replace("FHsaasZW",self.description);            			
            line=line.replace("FHSAAS_columns",fieldsII);
            '''line=line.replace("<fields>",fields.encode(encoding='UTF-8'));'''			
            print(line)			
            lineST=lineST+line+""			

        # 关闭文件
        #print(lineST)


        fo = open(path2, "w", encoding='UTF-8')
        fo.write(lineST)
        fo.close()      
        return True		
    def os_fieldsII_py(self):
        ls=""
		
        res = sorted(self.order_line, key=lambda l: l[0].id)			
		
        for line in res:
            if(line.ftype=="char"):		
                ls=ls+"    "+line.fen+"=fields.Char(u'"+line.fname+"',readonly=False,required=False,translate=False)"+"\n"

            if(line.ftype=="integer"):		
                ls=ls+"    "+line.fen+"=fields.Integer(u'"+line.fname+"',readonly=False,required=False,translate=False)"+"\n"	

            if(line.ftype=="float"):		
                ls=ls+"    "+line.fen+"=fields.Float(u'"+line.fname+"',readonly=False,required=False,translate=False)"+"\n"	

            if(line.ftype=="boolean"):		
                ls=ls+"    "+line.fen+"=fields.Boolean(u'"+line.fname+"',readonly=False,required=False,translate=False)"+"\n"	
				
            if(line.ftype=="selection"):		
                ls=ls+"    "+line.fen+"=fields.Selection([('0',u'KEY1'),('1',u'KEY2')],u'"+line.fname+"',readonly=False,required=False,translate=False)"+"\n"	
				
            if(line.ftype=="date"):		
                ls=ls+"    "+line.fen+"=fields.Date(u'"+line.fname+"',readonly=False,required=False,translate=False)"+"\n"	


            if(line.ftype=="datetime"):		
                ls=ls+"    "+line.fen+"=fields.Datetime(u'"+line.fname+"',readonly=False,required=False,translate=False)"+"\n"	

            if(line.ftype=="text"):		
                ls=ls+"    "+line.fen+"=fields.Text(u'"+line.fname+"',readonly=False,required=False,translate=False)"+"\n"	

            if(line.ftype=="function"):		
                ls=ls+"    "+line.fen+"=fields.Text(u'"+line.fname+"',readonly=False,required=False,translate=False)"+"\n"

            if(line.ftype=="many2one"):		
                ls=ls+"    "+line.fen+"=fields.Many2one('"+line.many2oneII+"',u'"+line.fname+"',readonly=False,required=False,translate=False)"+"\n"

            if(line.ftype=="many2many"):		
                ls=ls+"    "+line.fen+"=fields.Many2many('"+line.many2manyII+"','many2man_"+self.modle_id.fname+"_"+self.name+"_"+line.fen+"_rel', 'uid', 'gid', u'"+line.fname+"',)"+"\n"
				
	
				
        return ls		
		
    @api.model		
    def action_funproved0(self):
        #context = context or {}
        t=fields.datetime.now()
        #huid=self.get_employee(cr,uid,context)
        self.write({'Fstatus':'wait_prove','FAdddate':t})       
        return True
		
    @api.model		
    def action_funproved(self):
        #context = context or {}
        t=fields.datetime.now()
        #huid=self.get_employee(cr,uid,context)
        self.write({'Fstatus':'proved','FAdddate':t})       
        return True		
    @api.model		
    def create(self, vals):
        result = super(fhcode_tb_table002, self).create(vals)	
        return result
    @api.multi		
    def write(self, values):
	    
        result = super(fhcode_tb_table002, self).write(values)		
		
        return result
    @api.multi
    def unlink(self):
	
        return super(fhcode_tb_table002, self).unlink()
    @api.multi
    def copy(self, default=None):
        return super(fhcode_tb_table002, self).copy(default)
    @api.multi
    def search(self, args, offset=0, limit=None, order=None, context=None, count=False):
        domain =None		
        domain = [('Fstatus', '=', '0')]		
        return super(fhcode_tb_table002, self).search(args, offset=offset, limit=limit, order=order, count=count)		
fhcode_tb_table002() #对象定义结束
class fhcode_tb_table002line(models.Model):
    _name = 'fhcode.tb_table002line'
    _description = u'测试子表'
    #_rec_name='FClass'
    def get_employee(self, cr, uid, context={}):
        obj = self.pool.get('hr.employee')
        ids = obj.search(cr, uid, [('user_id','=',uid)])
        res = obj.read(cr, uid, ids, ['id','name'], context)
        return res and res[0]['id'] or 0
    pay_id=fields.Many2one('fhcode.tb_table002',u'fhcode_tb_table002',required=True, ondelete='cascade', index=True, copy=False)
    fkec=fields.Many2one('fhcode.tb_base',u'选择字段',)
    fkecsl=fields.Char(u'备注',readonly=False,required=False,translate=False)
    FAddperson =fields.Many2one('hr.employee',u'添加人',readonly=False,required=False,translate=False)
    FConsultant=fields.Many2one('hr.employee',u'班主任',readonly=False,required=False,translate=False)					   
    FAdddate= fields.Datetime(u'添加日期',readonly=False,required=False,translate=False)
    Fstatus=fields.Selection([('0',u'未分班'),('1',u'已分班')],u'是否分班',readonly=False,required=False,translate=False)					   
    FDisable=fields.Selection([('0',u'启用'),('1',u'停用')],u'是否停用',readonly=False,required=False,translate=False) 
	
fhcode_tb_table002line() #对象定义结束
